#include "CircleLinkList.h"

CircleLinkList *CircleLinkList::Init_CircleLinkList() {

    this->head.next = &(this->head);
    this->size = 0;

    return this;
}

void CircleLinkList::Insert_CircleLinkList(int pos, CircleLinkNode* data) {
    if(this == NULL) return;
    if(data == NULL) return;
    if(pos < 1 || pos > this->size + 1) {
        pos = this->size + 1;
    }
    //根据位置查找插入位置的前一个结点
    //辅助指针变量
    CircleLinkNode* pCurrent = &(this->head);
    for(int i = 1;i < pos;i++) {
        pCurrent = pCurrent->next;
    }

    //新数据入链表
    data->next = pCurrent->next;
    pCurrent->next = data;

    this->size++;
}

CircleLinkNode *CircleLinkList::Front_CircleLinkList() {
    if(this == NULL) return NULL;
    return this->head.next;
}

void CircleLinkList::RemoveByPos_CircleLinkList(int pos) {
    if(this == NULL) return;
    if(pos < 1 || pos > this->size) return;

    //根据pos找前一个结点
    //辅助指针变量
    CircleLinkNode* pCurrent = &(this->head);
    for(int i = 1;i < pos;i++) {
        pCurrent = pCurrent->next;
    }
    //缓存当前结点的下一个结点
    CircleLinkNode* pNext = pCurrent->next;
    pCurrent->next = pNext->next;
    pNext->next = NULL;

    this->size--;
}

void CircleLinkList::RemoveByValue_CircleLinkList(CircleLinkNode *data, COMPARENODE compare) {
    if(this == NULL) return;
    if(data == NULL) return;

    CircleLinkNode* pPrev =  &(this->head);
    CircleLinkNode* pCurrent = pPrev->next;
    for(int i = 1; i <= this->size;i++) {
        if(compare(pCurrent,data) == 0) {
            pPrev->next = pCurrent->next;
            pCurrent->next = NULL;
            this->size--;
            break;
        }
        pPrev= pCurrent;
        pCurrent = pPrev->next;
    }
}

int CircleLinkList::Size_CircleLinkList() {
    if(this == NULL) return -1;
    return this->size;
}

int CircleLinkList::IsEmpty_CircleLinkList() {
    if(this->size == 0) {
        return true;
    }
    return false;
}

int CircleLinkList::Find_CircleLinkList(CircleLinkNode *data, COMPARENODE compare) {
    if(this == NULL) return -1;
    if(data == NULL) return -1;

    CircleLinkNode* pCurrent = this->head.next;
    int flag = -1;
    for(int i = 1;i <= this->size;i++) {
        if(compare(pCurrent,data)) {
            flag = i;
            break;
        }
        pCurrent = pCurrent->next;
    }

    return flag;
}

void CircleLinkList::Print_CircleLinkList(PRINTNODE print) {
    if(this == NULL) return;

    CircleLinkNode* pCurrent = this->head.next;
    int flag = -1;
    for(int i = 1;i <= this->size * 3;i++) {
        if(pCurrent == &(this->head)) {
            pCurrent = pCurrent->next;
            printf("------------------------------------------\n");
        }
        print(pCurrent);
        pCurrent = pCurrent->next;
    }
}

void CircleLinkList::FreeSpace_CircleLinkList() {
    if(this == NULL) return;

    delete this;
}
